package com.hup.utils.swing;

import sun.swing.SwingUtilities2;

import javax.swing.*;
import java.awt.*;

/**
 * @author hugan
 * @date 2019/12/6
 */
public class DimensionUtil {

    /**
     * 获取文字尺寸,一般用于绘制
     */
    public static Dimension getTextSize(JComponent c, String str) {
        FontMetrics metrics = c.getFontMetrics(c.getFont());
        int width = metrics.stringWidth(str);
        int height = metrics.getHeight();
        return new Dimension(width, height);
    }

    /**
     * 用于根据传入字符串设置控件大小
     * @return 控件大小,包括insert!
     */
    public static Dimension getSizeByText(JComponent c, String str) {
        Insets insets = c.getInsets();
        FontMetrics metrics = c.getFontMetrics(c.getFont());
        int width = metrics.stringWidth(str);
        int height = metrics.getHeight();
        return new Dimension(insets.left + width +insets.right,
                insets.top + height +insets.bottom);
    }

    /**
     * 根据传入字符串设置控件大小
     * @param str 以'\n'为换行符的字符串
     * @param maxLine 最大行数,用于定义最大高度
     * @return 控件大小,包括insert!
     */
    @SuppressWarnings("Duplicates")
    public static Dimension getSizeByWrapText(JComponent c, String str, int maxLine) {
        FontMetrics metrics = c.getFontMetrics(c.getFont());
        String[] lines = str.split("\n");
        String longestLine = lines[0];
        for (String line : lines) {
            if (longestLine.length() < line.length()) {
                longestLine = line;
            }
        }
        int width = metrics.stringWidth(longestLine);
        int height = metrics.getHeight();//单行高度
        height = height * Math.min(lines.length, maxLine);
        Insets insets = c.getInsets();
        return new Dimension(insets.left + width +insets.right,
                insets.top + height +insets.bottom);
    }

    public static Dimension getSizeByWrapText(JComponent c, String[] lines) {
        FontMetrics metrics = c.getFontMetrics(c.getFont());
        String longestLine = lines[0];
        for (String line : lines) {
            if (longestLine.length() < line.length()) {
                longestLine = line;
            }
        }
        int width = metrics.stringWidth(longestLine);
        int height = metrics.getHeight();//单行高度
        return new Dimension(width, height * lines.length);
    }

    /**
     * 测量仅含数字的文本的大小
     * @param numText 仅含数字的文本
     */
    public static Dimension getSizeOfNumber(Font font, String numText) {
        FontMetrics metrics = SwingUtilities2.getFontMetrics(null, font);
        int fontHei = metrics.getAscent() - (metrics.getLeading() + metrics.getDescent());
        int fontWid = metrics.stringWidth(numText);
        return new Dimension(fontWid, fontHei);
    }

}
